<template>
  <div class="app-container" style="margin-top: -25px">
    <el-table  v-loading="loading"   :summary-method="getSummaries" show-summary :data="purchaseInfoApplyList" @selection-change="handleSelectionChange" row-key="columnId" :max-height="tableHeight">
      <el-table-column label="物料编号" align="center" prop="itemId" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="spec" />
      <el-table-column label="单位" width="80" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jc_iteminfo_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplyName">
        <!--<template slot-scope="scope">
          <el-select v-model="scope.row.supplyId" placeholder="请选择供应商" clearable>
            <el-option
              v-for="dict in supplierList"
              :key="dict.id"
              :label="dict.supplierName"
              :value="dict.id"
            />
          </el-select>
        </template>-->
      </el-table-column>
      <el-table-column label="项目订单号" align="center" prop="asnDanhao" />
      <el-table-column label="订单数量" align="center" prop="yddNum" />
       <!-- <template slot-scope="scope">
          <div style="display:flex">
            <el-input @click.native="clearYddNum(scope.row)"  clearable style="display:inline"v-model="scope.row.yddNum"></el-input>
          </div>
        </template>
      </el-table-column>-->
      <el-table-column label="往采数量" align="center" prop="shNum" >
<!--        <template slot-scope="scope">-->
<!--          <div style="display:flex">-->
<!--            <el-input @click.native="clearshNum(scope.row)"  clearable style="display:inline"v-model="scope.row.shNum"></el-input>-->
<!--          </div>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="包装数量" align="center" prop="packingNum" >
<!--        <template slot-scope="scope">-->
<!--          <div style="display:flex">-->
<!--            <el-input @click.native="clearpackingNum(scope.row)"  clearable style="display:inline"v-model="scope.row.packingNum"></el-input>-->
<!--          </div>-->
<!--        </template>-->
      </el-table-column>
      <!-- <el-table-column label="生产周期" align="center" prop="scDate">
         <template slot-scope="scope">
           <div style="display:flex">
             <el-input  clearable style="display:inline"v-model="scope.row.scDate"></el-input>
           </div>
         </template>
       </el-table-column>-->
      <el-table-column label="采购数量" align="center" prop="yhNum" >
<!--        <template slot-scope="scope">-->
<!--          <div style="display:flex">-->
<!--            <el-input @click.native="clearyhNum(scope.row)"  clearable style="display:inline"v-model="scope.row.yhNum"></el-input>-->
<!--          </div>-->
<!--        </template>-->
      </el-table-column>
      <!--<el-table-column label="计划单价"  align="center" prop="jhUnitPrice" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input-number style="width: 100%"  controls-position="right" clearable v-model="scope.row.jhUnitPrice" :precision="2"></el-input-number>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="计划总价"  align="center" prop="jhTotalPrice">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.jhUnitPrice*scope.row.yhNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>-->
      <el-table-column label="采购单价"  align="center" prop="unitPrice" >
<!--        <template slot-scope="scope">-->
<!--          <div style="display:flex">-->
<!--            <el-input @click.native="clearunitPrice(scope.row)" style="width: 100%"  controls-position="right" clearable v-model="scope.row.unitPrice" :precision="2"></el-input>-->
<!--          </div>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="采购总价"  align="center" prop="totalPrice">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.unitPrice*scope.row.yhNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="超出数量" align="center" prop="jhUnitPrice" >
        <template slot-scope="scope">
          <div style="display:flex;justify-content: center">
            <span style="text-align: center"> {{scope.row.yhNum - scope.row.yddNum}} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index,scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--选择物料-->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" style="margin-top: -20px"  :model="form" :rules="rules" label-width="80px">
        <IteminfoSelect ref="iteminfoSelect"></IteminfoSelect>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">选 择</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import {listApplyPurchaseInfo,addCaigoItemInfo} from "@/api/business/purchaseInfo";
  import {getLiSupplier} from "@/api/supplychain/supplier";
  import IteminfoSelect from '@/views/base/iteminfo/iteminfoSelect';

  export default {
    components: {
      IteminfoSelect
    },
    name: "PurchaseInfoApply",
    dicts: ['jc_iteminfo_unit'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        itemIds: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        isShow:false,
        // 采购详情表格数据
        purchaseInfoApplyList: [],
        //供应商档案数据
        supplierList: [],
        // 表格的高度
        tableHeight: document.documentElement.scrollHeight - 245 + "px",
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          caigouDanhao: null,
          itemName: null,
          itemId: null,
          supplyName: null,
          classId: null,
          className: null,
          caigouDate: null,
          purIds:[],
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      /* this.getList();*/
      this.getSuppList();
    },
    filters: {
      numFilter (value) {
        // 截取当前数据到小数点后两位
        let realVal = parseFloat(value).toFixed(2)
        return realVal
      }
    },
    methods: {
      clearYddNum(row){
        row.yddNum = ''
      },
      clearshNum(row){
        row.shNum = ''
      },
      clearpackingNum(row){
        row.packingNum = ''
      },
      clearyhNum(row){
        row.yhNum = ''
      },
      clearunitPrice(row){
        row.unitPrice = ''
      },
      /** 查询采购详情列表 */
      getList() {
        this.loading = true;
        /*  listCaigouDetail(this.queryParams).then(response => {
            this.purchaseInfoApplyList = response.rows;
            this.total = response.total;
            this.loading = false;
          });*/
      },
      getSuppList() {
        getLiSupplier().then(response => {
          this.supplierList = response.data;
        });
      },
      getCgInfoList(danhao){
        this.queryParams.caigouDanhao=danhao;
        this.getList()
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          caigouDanhao: null,
          itemName: null,
          itemId: null,
          supplyId: null,
          supplyName: null,
          classId: null,
          className: null,
          caigouNum: null,
          unitPrice: null,
          totalPrice: null,
          caigouDate: null,
          unit: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计';
            return;
          }
          if (index === 1 || index === 2 || index === 3 || index === 4 || index === 5 || index === 6 || index === 7 || index === 8 ) {
            return '';
          }
          for(var i=0 ;i<data.length;i++){
            data[i].totalPrice =data[i].yhNum*data[i].unitPrice;
            data[i].jhUnitPrice =data[i].yhNum-data[i].yddNum;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                if(index==4){
                  return prev + curr
                }else{
                  return this.keepTwoDecimalFull(Number(prev) + curr);
                }
              } else {
                return prev;
              }
            }, 0);
            sums[index];
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      keepTwoDecimalFull(num) {
        var result = parseFloat(num);
        if (isNaN(result)) {
          alert('传递参数错误，请检查！');
          return false;
        }
        result = Math.round(num * 100) / 100;
        var s_x = result.toString(); //将数字转换为字符串

        var pos_decimal = s_x.indexOf('.'); //小数点的索引值


        // 当整数时，pos_decimal=-1 自动补0
        if (pos_decimal < 0) {
          pos_decimal = s_x.length;
          s_x += '.';
        }

        // 当数字的长度< 小数点索引+2时，补0
        while (s_x.length <= pos_decimal + 2) {
          s_x += '0';
        }
        return s_x;
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /*重置列表*/
      purchaseInfoApplyListReset(ids){
        this.purchaseInfoApplyList =[];
        this.queryParams.purIds=ids;
        listApplyPurchaseInfo(this.queryParams).then(response => {
           this.purchaseInfoApplyList = response.rows;
           this.loading = false;
         });
      },
      /*修改*/
      purchaseInfoEditListReset(data){
        this.row = {
          factoryName: null,
          factoryCode: null,
          danhao: null,
          yhDanhao: null,
          asnDanhao: null,
          classId: null,
          className: null,
          itemName: null,
          itemId: null,
          itemCode: null,
          spec: null,
          unit: null,
          txm: null,
          supplyId: null,
          supplyName: null,
          makerCode: null,
          makerName: null,
          contractCode: null,
          contractNum: null,
          contractShare: null,
          totalPrice: null,
          unitPrice: null,
          isTuoguan: null,
          yhNum: null,
          shNum: null,
          rkNum: null,
          hgNum: null,
          thNum: null,
          yhType: null,
          yhCompany: null,
          wlCompany: null,
          dhCompany: null,
          yhTime: new Date(),
          dhStock: null,
          shName: null,
          shKuwei: null,
          shAddress: null,
          ghCompany: null,
          ghDate: null,
          ghAddress: null,
          scDate: null,
          gysYsjl: null,
          gysYssj: null,
          yddNum: null,
          ywcNum: null,
          yghwcbl: null,
          dxrl: null,
          ncgPlanId: null,
          ncgPlanNum: null,
          jcgPlanId: null,
          jcgPlanNum: null,
          ycgPlanId: null,
          ycgPlanNum: null,
          lscgPlanId: null,
          lscgPlanNum: null,
          size: null,
          singleWeight: null,
          totalWeight: null,
          rukuDate: null,
          upLine: null,
          downLine: null,
          stockSafe: null,
          useState: null,
          color: null,
          figure: null,
          caizhi: null,
          isDaizhi: null,
          packingNum: null,
          packingSize: null,
          packingCaizhi: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.isShow=false;
        this.purchaseInfoApplyList =[];
        this.purchaseInfoApplyList.push(data);
        this.loading = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "选择物料信息";
        this.itemIds=[];
        if(this.purchaseInfoApplyList.length>0){
          this.purchaseInfoApplyList.map((item) => {
            this.itemIds.push(item.itemCode);
          })
        }
        setTimeout(() => {
          this.$refs.iteminfoSelect.getItemInfoList(this.itemIds);
        }, 5);

      },
      /** 提交按钮 */
      submitForm() {
        const id =this.$refs.iteminfoSelect.ids;
        addCaigoItemInfo(id).then(response => {
          response.data.map((item)=>{
            this.purchaseInfoApplyList.push(item)
          })
        });
        this.open = false;
      },
      /** 删除按钮操作 */
      handleDelete(index,row) {
        this.purchaseInfoApplyList.splice(index,1);
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/caigouDetail/export', {
          ...this.queryParams
        }, `采购单导出_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style lang="scss" scoped>
  ::v-deep .el-input-number.is-controls-right .el-input-number__increase{
    display: none;
    visibility: hidden;
    width: 10px !important;
    position: fixed;
    top:0;
  }
  ::v-deep .el-input-number.is-controls-right .el-input-number__decrease{
    display: none;
    visibility: hidden;
    position: fixed;
    top:0;
  }
  ::v-deep .el-table .cell{
    /*display: none;*/
    padding-right: 0;
    padding-left: -30px;
  }
  /*  .el-input-number.is-controls-right .el-input__inner {
      padding-left: 4px;
      padding-right: 9px;
    }*/
</style>
